//
//  HMRefreshControl.swift
//  123
//
//  Created by pangjiaxing on 16/1/4.
//  Copyright © 2016年 pangjiaxing. All rights reserved.
//

import UIKit

enum HMRefreshControlState: Int {
    case Normal = 0         // 默认状态
    case Pulling = 1        // 松手就可以刷新的状态
    case Refreshing = 2     // 正在刷新的状态
}


private let HMRefreshControlH: CGFloat = 50
class HMRefreshControl: UIControl {
    
    // 箭头图标
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    // 显示当前状态的 label
    private lazy var messageLabel: UILabel = {
        let label = UILabel(textColor: UIColor.grayColor(), fontsize: 12)
        label.text = "下拉刷新"
        return label
    }()
    
    // 刷新中的状态控件
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView()

   
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.frame.size = CGSizeMake(mainScreenW, HMRefreshControlH)
        self.frame.origin.y = -self.frame.height
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        backgroundColor = RandomColor()
        
        addSubview(arrowIcon)
        addSubview(messageLabel)
        addSubview(indicatorView)
        
        // 添加约束
        
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-30)
        }
        
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(arrowIcon)
            make.leading.equalTo(arrowIcon.snp_trailing)
        }
        
        indicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon)
        }
    }
    
    weak var scrollView: UIScrollView?
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        if let scrollView = newSuperview as? UIScrollView {
           self.scrollView = scrollView
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: [NSKeyValueObservingOptions.New], context: nil)
            
            self.frame.size.width = scrollView.frame.width
        }
    }
    deinit {
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    // 这个方法是当前控件观察的 scrollView 身上的 contentOffset 改变了之后，就会回调
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        // 判断当前控件是否是真正的全部显示出来
        let contentInsetTop = scrollView!.contentInset.top
        //        print(contentInsetTop)系统值初始值64，然后不会变化
        // 通过测试可得，当 scrollView.contentOffset.y 为 -contentInsetTop-HMRefreshControlH
        //        print(scrollView?.contentOffset.y)初始值为-64 ，然后不断变化
        
        // 完全显示出来的条件
        let conditionValue = -contentInsetTop-HMRefreshControlH
        
        if scrollView!.dragging {
            if scrollView!.contentOffset.y <= conditionValue && refreshState == .Normal {
                refreshState = .Pulling
                print("松手就可去刷新状态\(scrollView!.contentOffset.y)")
            }else if scrollView!.contentOffset.y > conditionValue && refreshState == .Pulling {
                refreshState = .Normal
                print("松手就自去回去，保持默认状态\(scrollView!.contentOffset.y)")
            }
        }else{
            // 用户松手
            // 判断当前是否是 `松手就刷新` 状态，如果是，就去刷新
            if refreshState == .Pulling {
                // 如果当前用户已松手，并且当前控件全部显示出来(松手就去刷新的状态，.Pulling)
                refreshState = .Refreshing
                print("进入正在刷新的状态")
            }
        }
    }
    
    
    // 刷新控件之前的状态
    var oldRefreshState: HMRefreshControlState = .Normal
    // 当前刷新控件的状态
    var refreshState: HMRefreshControlState = .Normal {
        didSet{
            switch refreshState {
            case .Pulling: // 当前控件全部展示出来，执行箭头的旋转动画
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                messageLabel.text = "放开起飞"
            case .Normal:
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformIdentity
                })
                messageLabel.text = "下拉刷新"
                arrowIcon.hidden = false
                indicatorView.stopAnimating()
                
                // 只有从刷新状态到默认状态，才要把多出的滑动距离给减回去
                if oldRefreshState == .Refreshing {
                    UIView.animateWithDuration(0.5, animations: { () -> Void in
                        // 调整 contentInset的top值
                        var contentInset = self.scrollView!.contentInset
                        contentInset.top = contentInset.top - HMRefreshControlH
                        self.scrollView?.contentInset = contentInset
                    })
                }
            case .Refreshing:
                // 开始动画
                indicatorView.startAnimating()
                // 隐藏箭头
                arrowIcon.hidden = true
                messageLabel.text = "正在加载"
                
                UIView.animateWithDuration(0.5, animations: { () -> Void in
                    // 调整 contentInset的top值
                    var contentInset = self.scrollView!.contentInset
                    contentInset.top = contentInset.top + HMRefreshControlH
                    self.scrollView?.contentInset = contentInset
                })
                // 发送某个状态所在产生的事件
                sendActionsForControlEvents(.ValueChanged)
            }
            // 记录状态，以便下一次再设置 refreshState 的时候，可以取到上一次的状态
            oldRefreshState = refreshState
        }
    }
    func endRefreshing(){
        
        refreshState = .Normal
    }
}
